import { FC, ReactElement, useCallback, useMemo } from "react";
import { DayItem, DateGridContainer } from "./styled";

interface IProps {
  year: number;
  month: number;
  day: number;
  selectDay: (day: number) => () => void;
}

const DateGrid: FC<IProps> = ({
  year,
  month,
  day,
  selectDay,
}): ReactElement => {
  const [firstDay_Week, allDateThisMonth] = useMemo(
    () => [
      new Date(`${year}-${month}-1`).getDay(),
      new Date(year, month, 0).getDate(),
    ],
    [month, year]
  );

  const renderDate = useCallback(
    (_, index) => {
      let date: number = index - firstDay_Week + 1;
      date = date > 0 && date <= allDateThisMonth ? date : 0;
      if (!date) return <DayItem key={index} />;
      //是选中的日期
      if (date === day) {
        return (
          <DayItem
            onClick={selectDay(date)}
            style={{
              backgroundColor: "#51f",
              color: "#fff",
              fontWeight: "bold",
              fontSize: "0.7rem",
            }}
            key={index}
          >
            {date}
          </DayItem>
        );
      }

      return (
        <DayItem onClick={selectDay(date)} key={index}>
          {date}
        </DayItem>
      );
    },
    [allDateThisMonth, day, firstDay_Week, selectDay]
  );

  return (
    <DateGridContainer>
      {Array.from(Array(allDateThisMonth + firstDay_Week), renderDate)}
    </DateGridContainer>
  );
};

export default DateGrid;
